#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextFrame>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);                                     //即使auto了，但编译器仍旧没有这个类的声明和定义
    auto doc = ui->textEdit->document();//?#include <QTextDocument>
    auto root_frame = doc->rootFrame();//?#include <QTextFrame>这俩头文件只用添加这一个头文件吗,而且为什么auto了还要包含?
    QTextFrameFormat frame_format;
    frame_format.setBorderBrush(Qt::blue);
    frame_format.setBorder(1);
    root_frame->setFrameFormat(frame_format);
    ui->textEdit->insertPlainText("hello world!\n");
    ui->textEdit->insertPlainText("Hello Qt\n");

    QTextFrameFormat  frameFormat;
    frameFormat.setBackground(Qt::lightGray);
    frameFormat.setMargin(10);
    frameFormat.setPadding(5);
    frameFormat.setBorder(2);
    frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Dashed);
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.insertFrame(frameFormat);

    QAction* action_font = new QAction(tr("字体"), this);
    action_font->setCheckable(true);
    connect(action_font, &QAction::toggled, this, &MainWindow::setTextFont);
    ui->toolBar->addAction(action_font);

}

void MainWindow::setTextFont(bool checked)
{
    if(checked){
        QTextCursor cursor = ui->textEdit->textCursor();
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignCenter);
        cursor.insertBlock(blockFormat);
        QTextCharFormat charFormat;
        charFormat.setBackground(Qt::lightGray);
        charFormat.setForeground(Qt::blue);
        charFormat.setFont(QFont(tr("宋体"),12,QFont::Bold,true));
        charFormat.setFontUnderline(true);
        cursor.setCharFormat(charFormat);
        cursor.insertText(tr("插入字体"));
    }else{
        QTextCursor cursor = ui->textEdit->textCursor();
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignLeft);
        cursor.insertBlock(blockFormat);
        QTextCharFormat charFormat;
        //        charFormat.setBackground(Qt::white);
        //        charFormat.setForeground(Qt::black);
        //        charFormat.setFont(QFont(tr("微软雅黑"),12,QFont::Normal, false));
        //        charFormat.setFontUnderline(false);
        cursor.setCharFormat(charFormat);
        cursor.insertText(tr("微软雅黑字体"));
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
